package book.demo1.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        NioEventLoopGroup group = new NioEventLoopGroup(); // 1

        try {
            ServerBootstrap b = new ServerBootstrap();// 2
            b.group(group)
                    .channel(NioServerSocketChannel.class) // 3 指定传输所使用的的nio
                    .localAddress(new InetSocketAddress(port))  // 4 指定端口
                    .childHandler(new ChannelInitializer() {
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(serverHandler); // 5 添加一个EchoServer
                        }
                    });
            ChannelFuture f = b.bind().sync(); // 6
            f.channel().closeFuture().sync(); //7
        } finally {
            group.shutdownGracefully().sync(); // 8
        }
    }

    public static void main(String[] args) throws Exception {
        new EchoServer(8899).start();
    }
}
